from flask import Flask, render_template, request
import requests
from bs4 import BeautifulSoup
import chardet

app = Flask(__name__)

def get_page_info(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        
        # 检测网页内容的编码
        encoding = chardet.detect(response.content)['encoding']
        
        # 使用检测到的编码解码网页内容
        soup = BeautifulSoup(response.content.decode(encoding), 'html.parser')
        
        title = soup.find('title').string if soup.find('title') else 'No title found'
        keywords = soup.find('meta', {'name': 'keywords'})
        keywords = keywords['content'] if keywords else 'No keywords found'
        description = soup.find('meta', {'name': 'description'})
        description = description['content'] if description else 'No description found'
        
        return title, keywords, description
    except requests.exceptions.RequestException as e:
        return None, None, None

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        url = request.form['url']
        title, keywords, description = get_page_info(url)
        return render_template('index.html', title=title, keywords=keywords, description=description, url=url)
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
